package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {


    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Override
    public void save(Order order) {
        //1. 先获取当前登录用户
        User user = UserHolder.get();

        //2. 先查询到当前用户的购物车
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车是空的,无法生成订单");
        }

        //3. 根据前端传入的地址id查询地址信息
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址不存在,无法生成订单");
        }

        //4. 手动使用雪花算法生一个订单id
        Long orderId = IdWorker.getId();//mybatisplus工具类生成雪花算法的id

        BigDecimal total = new BigDecimal(0);//double total = 0
        //total += number * amount
        //5. 生成订单详情
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);//当前明细所属订单的id
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());

            //保存到数据表
            orderDetailMapper.insert(orderDetail);

            //每次遍历的时候添加金额
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));//total += amount * number
        }


        //6. 生成订单
        order.setId(orderId);//使用刚刚生成的orderid
        order.setNumber(orderId + "");//订单号 使用订单id
        order.setStatus(0);//待付款
        order.setUserId(user.getId());//登录用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//支付时间(支付的时候再更新一下)
        order.setAmount(total);//本次订单总金额=所有明细中单价*数量再相加
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);

        //7. 清空当前用户购物车
        cartService.clean();
    }

    /**
     * 订单信息查询
     */
    @Override
    public Page<Order> findByPage2(Long number, Date beginTime, Date endinTime, Integer pageNum, Integer pageSize) {
        //1.设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2.设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null, Order::getId, number);
        wrapper.ge(beginTime != null, Order::getOrderTime, beginTime);
        wrapper.le(endinTime != null, Order::getOrderTime, endinTime);

        //3.设置排序时间(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4.执行查询条件
        page = orderMapper.selectPage(page, wrapper);

        //5.遍历订单列表，得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6.根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        return page;
    }

    /*
     * 分页订单查询
     * */
    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {
        //1.设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2.设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());

        //3.设置排序(时间排序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4.执行查询，得到订单信息
        page = orderMapper.selectPage(page, wrapper);

        //5.遍历历史订单列表，得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6.根据订单id从详情表中获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        return page;
    }
}